//
//  BKComposeViewController.swift
//  微博
//
//  Created by mac on 16/8/16.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class BKComposeViewController: UIViewController {
    
    //  MARK: --  懒加载创建控件
    private lazy var sendButton:UIButton = {
    
        let rightBtn = UIButton()
        
        //设置不同状态的背景图片
        rightBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        rightBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        rightBtn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: .Disabled)
        
        //设置不同状体的文字颜色
        rightBtn.setTitle("发送", forState: .Normal)
        rightBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        rightBtn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        //设置大小
        rightBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        rightBtn.size = CGSize(width: 45, height: 30)
        
        //添加点击事件
        rightBtn.addTarget(self, action: "composeTweet", forControlEvents: .TouchUpInside)
        
        
        return rightBtn
    }()
    
    //标题视图
    private lazy var titleLabel:UILabel = {
    
        let label = UILabel(fontSize: 17, textColor: UIColor.darkGrayColor())
        
        if let name = BKUserAccountViewModel.shareUserAccount.userAccount?.name{
        
            let result = "发微博\n\(name)"
            
            //获取name的range
            let range = (result as NSString).rangeOfString(name)
            
            let attribuedStr = NSMutableAttributedString(string: result)
            
            attribuedStr.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(14)],range:range)
            
            label.attributedText = attribuedStr
        
        
        }else{
        
            label.text = "发微博"
        }
        
        label.numberOfLines = 0
        label.sizeToFit()
        label.textAlignment = .Center
        
        return label
        
    }()
    
    //发微博视图
    private lazy var textView:BKComposeTextView = {
    
        let textView = BKComposeTextView()
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(16)
        textView.autocorrectionType = .No
       //开启滑动效果,便于回收键盘
        textView.alwaysBounceVertical = true
        //textView.backgroundColor = UIColor.whiteColor()
        return textView
    }()
    
    //底部的toolBar
    private lazy var toolBar:BKToolBar = {
    
        let composeToolBar = BKToolBar(frame:CGRectZero)
        return composeToolBar
    }()
    //配图的view
    private lazy var pictureView:BKComposePictureView = {
    
        let view = BKComposePictureView()
        view.backgroundColor = self.textView.backgroundColor
        return view
    }()
    //emotionKeyBoard
    private lazy var emotionKeyBoard:BKEmotionKeyBoard = {
    
        let view = BKEmotionKeyBoard()
        view.backgroundColor = RandomColor()
        view.size = CGSize(width:self.textView.width, height: 216)
        return view
    }()
    
    
    //添加控件设置约束
    private func setupUI() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView.snp_width).offset(-10)
            make.height.equalTo(textView.snp_width).offset(-10)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(35)
        }
        toolBar.didSelecteToolBarButtonClosure = { [weak self] (type:BKToolBarType) in
        
            switch type {
            
            case.Picture:
                self?.didSelectedImage()
            case.Mention:
                print("@")
            case.Trend:
                print("#")
            case.Emoticon:
                print("表情")
                self?.didSelectedEmotion()
            case.Add:
                print("加号")
            }
        }
        
        pictureView.didSelectAddImageViewClosure = {[weak self] in
        
            self?.didSelectedImage()
        }
    }
    
    
    
    //  MARK: --  监听键盘改变的通知
    @objc private func keyBoardChange (noti:NSNotification){
        
        //print(noti.userInfo)
        
        //获取键盘的frame
        let keyBoardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey]as!NSNumber).doubleValue
        
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - self.view.height)
        }
        //更新约束动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    //点击发送按钮事件
    @objc private func composeTweet (){
        
        if pictureView.images.count > 0 {
        
            let status = textView.text!
            let accessToken = BKUserAccountViewModel.shareUserAccount.accessToken!
            let image = pictureView.images.first!
            
            SVProgressHUD.show()
            BKNetworkTools.shareTools.upload(accessToken, status: status, image: image, callBack: { (response, error) -> () in
                if error != nil{
                    
                    print(error)
                    SVProgressHUD.showErrorWithStatus("网络异常,发送失败")
                    return
                }else{
                    
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                }
                
            })
        }else{
        
            
            let status = textView.text!
            let access_token = BKUserAccountViewModel.shareUserAccount.accessToken!
            SVProgressHUD.show()
            BKNetworkTools.shareTools.updateStatus(access_token, status: status) { (response, error) -> () in
                
                if error != nil{
                    
                    print(error)
                    SVProgressHUD.showErrorWithStatus("网络异常,发送失败")
                    return
                }else{
                    
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                }

            }
    
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //view.backgroundColor = RandomColor()
        setupNavUI()
        setupUI()
    }
    
    
    //设置导航条视图
    private func setupNavUI() {
    
        //导航条左边的按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        //导航条右边的按钮 需要自定义
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView:sendButton)
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleLabel
        
    }
    //左按钮点击事件
    @objc private func cancelAction () {
    
        dismissViewControllerAnimated(true, completion: nil)
        
        self.view.endEditing(true)
    }
    
    

}

//  MARK:   -实现UITextViewDelegate代理方法
extension BKComposeViewController:UITextViewDelegate{

    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        
        self.view.endEditing(true)
    }
}

//  MARK:   -- 点击toolBar的处理逻辑
extension BKComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //处理表情按钮逻辑
    func didSelectedEmotion(){
    
        if textView.inputView == nil{
        
            textView.inputView = emotionKeyBoard
            toolBar.switchEmotionIcon(true)
        }else{
        
            textView.inputView = nil
            toolBar.switchEmotionIcon(false)
        }
        
        textView.becomeFirstResponder()
        textView.reloadInputViews()
    }
    

    func didSelectedImage(){
    
        let picCtr = UIImagePickerController()
        picCtr.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.Camera){
        
            picCtr.sourceType = .Camera
        }else{
        
            picCtr.sourceType = .PhotoLibrary
        }
        
        //判断前置摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.Front){
        
            print("前置摄像头可用")
        }else if UIImagePickerController.isCameraDeviceAvailable(.Rear){
        
            print("后置摄像头可用")
        }else{
        
            print("没有摄像头")
        }
        
        presentViewController(picCtr, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleImageWithScaleWidth(200)
        
        pictureView.addImage(scaleImage)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

    
}



